﻿using System.Collections.Generic;
using System.Linq;

namespace Fujitsu.JiraAnalysis.DAL
{
    public class UserStorage
    {
        public User GetUser(int userId)
        {
            using (var db = new JiraAnalysisDBEntities())
            {
                return db.User.FirstOrDefault(u => u.ID == userId);
            }
        }

        public List<User> GetUsers()
        {
            using (var entityModel = new JiraAnalysisDBEntities())
            {
                return (from u in entityModel.User
                        select u).ToList();
            }
        }

        public int AddOrUpdateUser(string login, string firstNmae, string lastName)
        {
            using (var entityModel = new JiraAnalysisDBEntities())
            {
                var user = (from u in entityModel.User
                             where u.Login == login && u.FirstName == firstNmae && u.LastName == lastName
                             select u).FirstOrDefault();
                if (user != null)
                {
                    return user.ID;
                }
                var newUser = new User
                               {
                                   Login = login,
                                   FirstName = firstNmae,
                                   LastName = lastName
                               };

                entityModel.AddToUser(newUser);
                entityModel.SaveChanges();

                return newUser.ID;
            }
        }
    }
}
